package com.xinjixian.webgame;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.http.SslError;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smarx.notchlib.NotchScreenManager;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import static com.bun.miitmdid.core.JLibrary.context;

public class MainActivity extends AppCompatActivity {
    String deviceid = null;
    private WebView webView;
    private ImageView textview, ivTips;
    private TextView tv_title;
    private LinearLayout llSave, llTips;
    private long exitTime;
    public final int REQUEST_READ_PHONE_STATE = 101;
    private String IMEI;
    private String userName;
    private String password;
    private String loadUrl;
    private MediaPlayer mPlayer;
    private WifiStateReceiver wifiStateReceiver;
    private String redirect_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setFullScreen();
        NotchScreenManager.getInstance().setDisplayInNotch(this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 全屏、隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        textview = (ImageView) findViewById(R.id.tv_back);
        llSave = (LinearLayout) findViewById(R.id.ll_save);
        llTips = (LinearLayout) findViewById(R.id.ll_tips);
        ivTips = (ImageView) findViewById(R.id.iv_tips);
        tv_title = (TextView) findViewById(R.id.navigation_title);
        webView = (WebView) findViewById(R.id.wv);
        textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!webView.canGoBack()) {
                    return;
                } else {
                    webView.goBack();// 返回前一个页面
                }
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                // TODO Auto-generated method stub
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub
                super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }

            @Override
            public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                // TODO Auto-generated method stub
                super.onUnhandledKeyEvent(view, event);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                /*if (url.contains("/pay/success/wechat")) {
                    Log.e("123456_goBack", url);
                    webView.goBack();
                    return true;
                }*/
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                tv_title.setText(view.getTitle());
                if (Build.VERSION.SDK_INT < 18) {
                    webView.loadUrl("javascript:setDeviceId(" + "'" + IMEI + "'," + "'" + MyApplication.OAID + "'," + "'" + deviceid + "'" + ")");
                } else {
                    webView.evaluateJavascript("javascript:setDeviceId(" + "'" + IMEI + "'," + "'" + MyApplication.OAID + "'," + "'" + deviceid + "'" + ")", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            //此处为 js 返回的结果
                        }
                    });
                }
                Log.e("123456", "'" + IMEI + "'," + "'" + MyApplication.OAID + "'," + "'" + deviceid + "'");
            }


        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setAllowFileAccess(true);// 设置允许访问文件数据
        webView.getSettings().setSupportMultipleWindows(false);// 设置允许开启多窗口
        //绑定android对象到javascript对象，"obj"可以随意起名，与js端约定一致就好
        webView.addJavascriptInterface(this, "Androidobj");
        //if (MyApplication.AGENT_ID != null && !MyApplication.AGENT_ID.equals(""))
        //webView.loadUrl("http://open" + MyApplication.AGENT_ID + ".game.piu4.com/");
        // webView.loadUrl("http://open0.game.36500.net/portal/channellogin/index?gid=" + MyApplication.GAMEID);

        String result = getResources().getString(R.string.apk_url);
        Log.e("12356", result);
        webView.loadUrl(result);

        //test_key是properties文件中的key值
      /*  ResourceBundle bundle = ResourceBundle.getBundle("gradle");//gradle为properties的文件名
        String result = bundle.getString("APK_URL");//test_key是properties文件中的key值*/
        DownloadUtils.getExample(this).downloadApk();
        Log.e("123456", "00000");
        sendReceiver();
        getDeviceid();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopReceiver();
    }

    @JavascriptInterface
    public void screenshot(String userName, String password, String loadUrl) {
        checkPermission();
        this.userName = userName;
        this.password = password;
        this.loadUrl = loadUrl;
        shortView(llSave);
    }

    @JavascriptInterface
    public String jsGetDeviceId() {
        getDeviceid();
        return "";
    }

    @JavascriptInterface
    public void jsGetDownBox() {
        DownloadUtils.getExample(this).installApk();
    }

    /**
     * 获取设备信息
     */
    @SuppressLint("SetJavaScriptEnabled")
    public void getDeviceid() {
        deviceid = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        try {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_READ_PHONE_STATE);
            }
            IMEI = telephonyManager.getDeviceId();
        } catch (Exception e) {

        }
        //调用有参方法
        if (Build.VERSION.SDK_INT < 18) {
            webView.loadUrl("javascript:setDeviceId(" + "'" + IMEI + "'," + "'" + MyApplication.OAID + "'," + "'" + deviceid + "'" + ")");
        } else {
            webView.evaluateJavascript("javascript:setDeviceId(" + "'" + IMEI + "'," + "'" + MyApplication.OAID + "'," + "'" + deviceid + "'" + ")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        }
        Log.e("123456", "'" + IMEI + "'," + "'" + MyApplication.OAID + "'," + "'" + deviceid + "'");
        NotificationUtils.getExample(this).getNotificationUtils(IMEI, MyApplication.OAID, deviceid);
    }

    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};
    List<String> mPermissionList = new ArrayList<>();

    // private ImageView welcomeImg = null;
    private static final int PERMISSION_REQUEST = 1;

    private void checkPermission() {
        mPermissionList.clear();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        }
        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        //请求权限方法
        String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
        ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST);

    }

    /**
     * 播放来电和呼出铃声
     *
     * @param mContext
     */
    private void playFromRawFile(Context mContext) {
        AssetManager assetManager = getAssets();

        AssetFileDescriptor afd = null;
        try {
            afd = assetManager.openFd("samsara.mp3");
            mPlayer = new MediaPlayer();

            mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());

            mPlayer.prepare();

            mPlayer.start();

        } catch (IOException e) {
            Log.e("123456", "IOException");
            e.printStackTrace();
        }
    }

    /**
     * 显示截图提示
     *
     * @param bitmap
     */
    public void showTips(Bitmap bitmap) {
        ivTips.setImageBitmap(bitmap);
        llTips.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                llTips.setVisibility(View.GONE);
            }
        }, 3000);//3秒后执行Runnable中的run方法
        playFromRawFile(this);

    }

    /**
     * 设置截图文字
     *
     * @param llSave
     */
    private void shortView(LinearLayout llSave) {
        Log.e("SaveImage", "shortView");
        TextView tvUserName = (TextView) llSave.findViewById(R.id.tv_user_name);
        tvUserName.setText("账号：" + userName);
        TextView tvPassWord = (TextView) llSave.findViewById(R.id.tv_password);
        tvPassWord.setText("密码：" + password);
        Bitmap bitmap = QRCode.createQRCodeBitmap(loadUrl, 800, 800, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
        ImageView ivLoad = (ImageView) llSave.findViewById(R.id.iv_load);
        bitmap = BitmapFillet.fillet(bitmap, 20, BitmapFillet.CORNER_ALL);
        ivLoad.setImageBitmap(bitmap);
        Log.e("SaveImage", "SaveImage.viewShot");
        SaveImage.viewShot(llSave, MainActivity.this);
    }

    //退出确认
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出游戏", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //设置全屏
    private void setFullScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//Android9以上 允许内容延伸至安全区
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        getWindow().setAttributes(lp);
//隐藏状态栏
        hideStatusBarAndFullScreen();
    }

    //设置全屏并且 隐藏状态栏
    private void hideStatusBarAndFullScreen() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideStatusBarAndFullScreen();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ_PHONE_STATE:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    getDeviceid();
                }
                break;
            case PERMISSION_REQUEST:
                shortView(llSave);
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    private void sendReceiver() {
        Log.i("tag", "sendReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        wifiStateReceiver = new WifiStateReceiver();
        registerReceiver(wifiStateReceiver, filter);
    }

    private void stopReceiver() {
        Log.i("tag", "stopReceiver");
        if (wifiStateReceiver != null) {
            unregisterReceiver(wifiStateReceiver);
            wifiStateReceiver = null;
        }
    }
}
